<template>
  <div class="base-login">
    <div class="gray-bg">
      <div class="name-wrapper">
        <div content="诸暨市" class="city">
          {{ city }}
        </div>
        <div class="name">
          <span>{{ cnName }}</span>
          <span>{{ enName }}</span>
        </div>
      </div>
      <div class="login-content">
        <div class="title">
          <span>{{ loginType == 0 ? '账号登录' : '扫码登录' }}</span>
          <div class="type-tips">
            <span>{{ loginType == 0 ? '扫码登录' : '账号登录' }}</span>
            <span></span>
          </div>
          <div class="type-icon" @click="loginType = !loginType">
            <i
              class="iconfont"
              :class="loginType == 0 ? 'icon-qrcode' : 'icon-mimadenglu'"
            ></i>
            <div></div>
          </div>
        </div>
        <!-- 账号密码登录 -->
        <div class="login-form">
          <el-form
            v-if="loginType == 0"
            :model="form"
            ref="form"
            :rules="rules"
            label-width="0"
            :inline="false"
            size="large"
          >
            <el-form-item prop="usercode">
              <el-input v-model="form.usercode" placeholder="账号"></el-input>
            </el-form-item>
            <el-form-item prop="pwd">
              <el-input
                v-model="form.pwd"
                placeholder="密码"
                :type="showPwd ? '' : 'password'"
              >
                <i
                  slot="suffix"
                  class="eye-status iconfont el-input__icon"
                  :class="showPwd ? 'icon-eye' : 'icon-no_eye'"
                  @click="showPwd = !showPwd"
                ></i>
              </el-input>
            </el-form-item>
            <el-form-item prop="captcha">
              <div class="captcha">
                <el-input
                  v-model="form.captcha"
                  placeholder="验证码"
                  @keyup.enter.native="login"
                >
                  <span slot="prefix" class="el-input__icon">
                    <i class="el-icon-lock"></i>
                  </span>
                </el-input>
                <img
                  class="login-captcha"
                  :src="captchaPath"
                  @click="getCaptcha()"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button style="width: 100%" type="primary" @click="login"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
          <iframe
            v-if="loginType == 1"
            width="360px"
            height="360px"
            :src="qrUrl"
            frameborder="0"
          ></iframe>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getMenu, login, scanDDLogin } from '@/api/Index';
import MenuProvider from './MenuProvider';
// import localRoute from "@/mock/route";
import localRoutes from '@/router/localRoutes';
var md5 = require('md5');
export default {
  mixins: [MenuProvider],
  data() {
    return {
      city: '诸暨市',
      cnName: '公共投资项目全生命周期监管系统',
      enName: 'Life ciycle supervision system for public investment projects',
      // 登录状态 0 账号密码登录 1 扫码登录
      loginType: 1,
      captchaPath: '',
      form: {
        usercode: '',
        pwd: '',
        captcha: '',
        uuid: ''
      },
      rules: {
        usercode: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        pwd: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        captcha: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      },
      showPwd: false,
      qrUrl: `${scan_url}/oauth2/auth.htm?response_type=code&client_id=${client_id}&redirect_uri=${redirect_url}&scope=get_user_info&authType=QRCODE&embedMode=true`
    };
  },
  methods: {
    // 获取验证码
    getCaptcha() {
      this.form.uuid = this.getUUID();
      // this.captchaPath = `${base_url}/user/captcha?uuid=${this.form.uuid}`;
      this.captchaPath = `/api/user/captcha?uuid=${this.form.uuid}`;
    },
    getUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        return (
          c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8'
        ).toString(16);
      });
    },
    login() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.password = md5(this.form.pwd + 'saltbyzhuji2022');
          this.form.pwd = '';
          login(this.form)
            .then((res) => {
              if (res.code == 0) {
                localStorage.setItem('user', JSON.stringify(res.data));
                localStorage.setItem('token', res.data.token);
                this.initMenu();
              }
            })
            .catch(() => {
              this.getCaptcha();
            })
            .finally(() => {
              this.$refs.form.clearValidate();
              this.form.captcha = '';
            });
        }
      });
    },
    initMenu() {
      getMenu().then((res) => {
        if (res.code == 0) {
          let asyncRoutes = res.data || [];

          this.$store.commit('system/SET_Menu', asyncRoutes);

          let routes = this.transformRouter(asyncRoutes.concat(localRoutes));

          this.$store.commit('system/SET_ROUTES', routes);

          this.$router.addRoute({
            name: 'Index',
            path: '/',
            redirect: '/home',
            component: () => import('@/components/layout/Index.vue'),
            children: routes
          });

          this.$router.replace({ path: '/home' });
        }
      });
    },
    // 路由格式转换
    transformRouter(list) {
      return list.map((item) => {
        if (item.children) this.transformRouter(item.children);

        if (item.link_url != undefined) {
          item.name = item.link_url;
          item.path = item.link_url;
        }
        if (item.Component && item.menu_type == 2) {
          item.component = () => import(`@/${item.Component}.vue`);
        } else {
          item.component = { render: (e) => e('router-view') };
        }
        return item;
      });
    },
    // initMenu() {
    //   getMenu().then((res) => {
    //     // this.$store.commit("system/SET_Menu", res.data);
    //     if (res.code == 0) {
    //       let allowed = this.recursionRoute(localRoute, res.data);
    //       console.log(allowed);
    //       this.$store.commit("system/SET_ROUTES", allowed);
    //     }
    //   });
    // },
    // recursionRoute(local, allow) {
    //   local.map((l) => {
    //     if (l.children && l.children.length > 0) {
    //       l.children = this.recursionRoute(l.children)
    //     }else{
    //       allow.map((a) => {
    //         if(l.)
    //       });
    //     }
    //   });

    //   return local;
    // },
    dingLogin(e) {
      const code = e.data && e.data.code;
      if (code) {
        // 根据 code 去获取用户信息

        scanDDLogin({
          code: code
        }).then((res) => {
          if (res.code == 0) {
            localStorage.setItem('user', JSON.stringify(res.data));
            localStorage.setItem('token', res.data.token);
            this.initMenu();
          }
        });
      }
    }
  },
  created() {
    this.getCaptcha();
  },
  mounted() {
    window.addEventListener('message', this.dingLogin);
  }
};
</script>

<style lang="scss" scoped>
@import '@/assets/animation.scss';

.base-login {
  height: 100%;
  background: url('/public/img/base-login.jpg') 100% 100% no-repeat;
}
.gray-bg {
  width: 80%;
  min-width: 1000px;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 300px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 5px;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding: 50px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
.name-wrapper {
  color: #fff;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #fff;
  box-sizing: border-box;
  padding: 0 0 20px 0;
  .city {
    font-size: 36px;
    margin-right: 20px;
    font-weight: 900;
    position: relative;
    color: rgb(245, 216, 72);
    &::before {
      position: absolute;
      height: 50%;
      content: attr(content);
      overflow: hidden;
      color: #fff;
      z-index: 1;
    }
  }
  .name {
    display: flex;
    flex-direction: column;
    span {
      &:nth-child(1) {
        font-size: 24px;
        letter-spacing: 3px;
        margin-bottom: 3px;
      }
      &:nth-child(2) {
        font-size: 14px;
      }
    }
  }
}
.login-content {
  width: 500px;
  min-height: 400px;
  background-color: #fff;
  border-radius: 5px;
  box-sizing: border-box;
  padding: 20px;
  > .title {
    display: flex;
    align-items: center;
    > span {
      font-size: 20px;
      letter-spacing: 2px;
      font-weight: 600;
      margin-right: auto;
    }
    > .type-tips {
      margin-right: 10px;
      display: flex;
      align-items: center;
      span {
        &:nth-child(1) {
          box-sizing: border-box;
          padding: 3px 5px;
          font-size: 13px;
          color: $colorBlue;
          font-weight: 600;
          border: 1px solid $colorBlue-1;
          border-radius: 3px;
          background: $colorBlue-2;
        }
        &:nth-child(2) {
          display: inline-block;
          width: 0;
          height: 0;
          border: 6px solid transparent;
          border-left: 10px solid $colorBlue;
        }
      }
    }
    > .type-icon {
      height: 100%;
      position: relative;
      cursor: pointer;
      &:hover {
        > div {
          top: 50px;
          left: -50px;
        }
      }
      > i {
        font-size: 24px;
        color: $colorBlue;
      }
      > div {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(-135deg, transparent 20px, #fff 0);
      }
    }
  }
}
.login-form {
  box-sizing: border-box;
  padding: 60px 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.captcha {
  width: 100%;
  display: flex;
  align-items: center;
  .login-captcha {
    margin-left: 10px;
    width: 150px;
    cursor: pointer;
  }
}
</style>
<style lang="scss">
.el-input__inner {
  // height: 60px;
  // background-color: rgb(245, 245, 245);
  // color: #606266;
  // font-weight: 600;
}
.el-button {
  // height: 60px;
}

.eye-status {
  &:hover {
    cursor: pointer;
    color: #000;
  }
}
</style>
